<template>
  <div>
    <NavBar>
      <template #default>购物车</template>
    </NavBar>
    <ShopCartList
      :shopCartData="cartItems"
      @changeShopCartData="changeShopCart"
      @changeNumber="changeProductNumber"
      @deleteProduct="deleteGoalProduct"
    />
    <CheckoutBar
      :shopCartData="cartItems"
      :selectedCount="selectedCount"
      :totalPrice="totalPrice"
      :selectAll="selectAll"
      @toggleSelectAll="toggleSelectAll"
      @checkout="handleCheckout"
    />

    <PaymentDialog
      v-model="showPaymentDialog"
      :order-items="selectedItems"
      :total-amount="totalPrice"
      :user-id="userStore.userAccount.userId"
      @payment-success="handlePaymentSuccess"
    />
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useCartStore } from '@/stores/cartStore'
import { useUserStore } from '@/stores/userStore'
// import { useOrderStore } from '@/stores/orderStore'
import NavBar from '@/components/common/NavBar.vue'
import ShopCartList from '@/components/content/ShopCartList.vue'
import CheckoutBar from '@/components/content/CheckoutBar.vue'
import PaymentDialog from '@/components/content/PaymentDialog.vue'
import { ElMessage } from 'element-plus'

const cartStore = useCartStore()
const userStore = useUserStore()
// const orderStore = useOrderStore()

const selectAll = ref(false)
const showPaymentDialog = ref(false)
const cartItems = ref([])

const selectedItems = computed(() =>
  cartItems.value.filter(item => item.checked).map(item => ({
    cartId: item.cartId,
    productId: item.productId,
    productName: item.productName,
    price: item.price,
    quantity: item.quantity
  }))
)

const selectedCount = computed(() =>
  cartItems.value.filter(item => item.checked).length
)

const totalPrice = computed(() =>
  cartItems.value.reduce((sum, item) =>
    item.checked ? sum + (item.price * item.quantity) : sum, 0)
)

const initCartItems = () => {
  cartItems.value = cartStore.items.map(item => ({
    ...item,
    checked: false
  }))
}

const toggleSelectAll = (checked) => {
  selectAll.value = checked
  cartItems.value.forEach(item => {
    item.checked = checked
  })
}

const changeShopCart = (index, checked) => {
  cartItems.value[index].checked = checked
  selectAll.value = cartItems.value.every(item => item.checked)
}

const changeProductNumber = async (index, sign, number) => {
  const item = cartItems.value[index]
  if (item) {
    await cartStore.updateCartQuantity(item.cartId, sign, true)
    item.quantity += sign
  }
}

const deleteGoalProduct = async (index) => {
  const item = cartItems.value[index]
  if (item) {
    await cartStore.removeFromCart(item.cartId)
    cartItems.value.splice(index, 1)
    selectAll.value = cartItems.value.length > 0 &&
                     cartItems.value.every(item => item.checked)
  }
}

const handleCheckout = async () => {
  const selectedItems = cartItems.value.filter(item => item.checked)
  console.log('准备结算的商品:', selectedItems)

  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  if (!userStore.isLogin) {
    ElMessage.warning('请先登录')
    return
  }

  showPaymentDialog.value = true
}

const handlePaymentSuccess = async ({ cartIds }) => {
  try {
    // 确保 cartIds 是数组且不为空
    if (!cartIds || !Array.isArray(cartIds) || cartIds.length === 0) {
      throw new Error('无效的购物车ID列表')
    }

    // 删除购物车项
    await cartStore.removeMultipleFromCart(cartIds)

    // 更新本地购物车列表 - 确保使用响应式方式
    cartItems.value = cartItems.value.filter(item => !cartIds.includes(item.cartId))

    // 重置全选状态
    selectAll.value = false

    ElMessage.success('支付成功，已移除已购商品')
  } catch (error) {
    console.error('支付成功后的处理失败:', error)
    ElMessage.error(error.message || '支付成功后的处理失败')
  } finally {
    showPaymentDialog.value = false
  }
}

// 在父组件 mounted 中
onMounted(async () => {
  try {
    await cartStore.initCart()
    console.log('初始化购物车数据:', cartStore.items)
    initCartItems()
    console.log('格式化后的购物车数据:', cartItems.value)
  } catch (error) {
    console.error('初始化购物车失败:', error)
  }
})
</script>